<?php

CMS::File('form/field/select');

class Form_Field_Date extends Form_Field {

	private $year;
	private $month;
	private $day;
	private $hour;
	private $minute;
	private $second;

	protected $value;

	public function __construct($name){
	
		parent::__construct($name);

		// Construct selects.

		// Year (best guess)

		$this->year = new Form_Field_Select('year');
		$date = getdate(time());
		for($i = ($date['year'] - 5); $i <= ($date['year'] + 5); $i ++){
			$this->year->option($i, $i);
		}

		$this->month = new Form_Field_Select('month');
		for($i = 1; $i <= 12; $i ++){
			$this->month->option($i, $i);
		}

		$this->day = new Form_Field_Select('day');
		for($i = 1; $i <= 31; $i ++){
			$this->day->option($i, $i);
		}

		$this->hour = new Form_Field_Select('hour');
		for($i = 0; $i <= 23; $i ++){
			$this->hour->option($i, $i);
		}

		$this->minute = new Form_Field_Select('minute');
		for($i = 0; $i <= 60; $i ++){
			$this->minute->option($i, $i);
		}

		$this->second = new Form_Field_Select('second');
		for($i = 0; $i <= 60; $i ++){
			$this->second->option($i, $i);
		}


		// Set a sensible default
		$this->value(time());

	}

	public function value($value){
		// Unix timestamp $value

		$this->value = $value;

		$info = getdate($value);

		$this->year->value($info['year']);
		// make sure it is an option!
		$this->year->option((int) $info['year'], (int) $info['year']);

		$this->month->value($info['mon']);
		$this->day->value($info['mday']);
		$this->hour->value($info['hours']);
		$this->minute->value($info['minutes']);
		$this->second->value($info['seconds']);

	}

	public function output($base){
		$tpl = Output::getInstance()->Template(array('form','field','date'));
		$tpl->title = $this->title;
		$base[] = $this->name;
		$tpl->name = $base;
		$tpl->year = $this->year->output($base);
		$tpl->month = $this->month->output($base);
		$tpl->day = $this->day->output($base);
		$tpl->hour = $this->hour->output($base);
		$tpl->minute = $this->minute->output($base);
		$tpl->second = $this->second->output($base);
		return parent::output($base, $tpl);
	}

	public function run($value){
		$this->year->run(isset($value['year']) ? $value['year'] : null);
		$this->month->run(isset($value['month']) ? $value['month'] : null);
		$this->day->run(isset($value['day']) ? $value['day'] : null);
		$this->hour->run(isset($value['hour']) ? $value['hour'] : null);
		$this->minute->run(isset($value['minute']) ? $value['minute'] : null);
		$this->second->run(isset($value['second']) ? $value['second'] : null);
	
		$this->value(mktime(
			$this->hour->getValue(), 
			$this->minute->getValue(), 
			$this->second->getValue(), 
			$this->month->getValue(), 
			$this->day->getValue(), 
			$this->year->getValue()
		));
	}
	
	public function data(){
		return $this->value;
	}

}
